package com.googlecode.mvchat.server;

import java.net.Socket;
import java.util.ArrayList;

import org.apache.commons.lang3.ArrayUtils;

import com.googlecode.mvchat.protocol.Message;

public class ClientThread extends Thread {

	private Socket sock;
	private ArrayList<ConnectedClient> clients = new ArrayList<ConnectedClient>();


	public ClientThread(Socket s, ArrayList<ConnectedClient> clients){
		this.clients = clients;
		sock = s;
	}

	@Override
	public void run(){
		try{
			while(!sock.isClosed()){
				System.out.println("Waiting for input...");
				int b;
				ArrayList<Byte> byteList = new ArrayList<Byte>();
				while((b = sock.getInputStream().read()) != ((int)'\n')){
					byteList.add((byte)b);
				}
				Byte[] byteArr = new Byte[byteList.size()];
				byteList.toArray(byteArr);

				String message = new String(ArrayUtils.toPrimitive(byteArr));
				System.out.println(message);
				String[] splitMsg = message.split(";");
				if(splitMsg.length != 3){
					System.out.println("Someone's trying to kill us, man!");
					sock.close();
					return;
				}
				long sender = Long.parseLong(splitMsg[0]);
				long reciever = Long.parseLong(splitMsg[1]);
				boolean sent = false;
				if(reciever != -1L){
					for(ConnectedClient cc : clients){
						if(cc.id == reciever){
							Message msg = new Message();
							msg.setMessage(splitMsg[2]);
							msg.setReciever(reciever);
							msg.setSender(sender);
							cc.s.getOutputStream().write(msg.toBytes());
							System.out.println("Relayed message.");
							sent = true;
						}	
					}
					if(!sent){
						System.out.println("Unable to find recipient, sending error back.");
						Message msg = new Message();
						msg.setMessage("Could not find client with id "+reciever+".");
						msg.setSender(-1L);
						msg.setReciever(sender);
						sock.getOutputStream().write(msg.toBytes());
					}
				}else{
					ConnectedClient cc = new ConnectedClient();
					cc.id=sender;
					cc.s = sock;
					clients.add(cc);
					System.out.println("New client (ID: "+cc.id+") connected and registered.");
					continue;
				}
			}
		}catch(Exception e){
			System.out.println("EXCEPTION!!!!!!111111");
			e.printStackTrace();
		}
	}
}
